package com.wuyou.securitydemo.handler;

import cn.hutool.core.util.CharsetUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wuyou.sso.common.utils.AuthUtils;
import com.wuyou.securitydemo.component.CustomizedTokenService;
import com.wuyou.securitydemo.domain.TokenVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * CustomizedAuthenticationSuccessHandler
 *
 * @Date 2025/4/1 15:09
 * @Author 无忧
 */
@Slf4j
@Component
public class CustomizedAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private static final String BASIC_ = "Basic ";

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private CustomizedTokenService tokenService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // Basic xxx -> 请求客户端名称
        String header = request.getHeader(HttpHeaders.AUTHORIZATION);

        if (header == null || !header.startsWith(BASIC_)) {
            throw new IllegalAccessError("请求头中client信息为空");
        }

        try {
            String[] tokens = AuthUtils.extractAndDecodeHeader(header);
            assert tokens.length == 2;
            String clientId = tokens[0];

            // 校验secret
//            if (!passwordEncoder.matches(tokens[1], clientDetails.getClientSecret())) {
//                throw new InvalidClientException("Given client ID does not match authenticated client");
//            }

//            CustomizedPasswordAuthenticationToken token = tokenService.createToken(authentication, "deviceId", AuthConstants.TOKEN_VALID_TIME_IN_SECOND, false, 3, Collections.emptyList());

//            CustomizedPasswordAuthenticationToken authenticationToken = (CustomizedPasswordAuthenticationToken) authentication;
            TokenVO token = tokenService.createToken(authentication);
//            TokenRequest tokenRequest =
//                    new TokenRequest(MapUtil.newHashMap(), clientId, clientDetails.getScope(), "openid");
//
//            // 校验scope
//            new DefaultOAuth2RequestValidator().validateScope(tokenRequest, clientDetails);
//            OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
//            OAuth2Authentication oAuth2Authentication =
//                    new OAuth2Authentication(oAuth2Request, authentication);
//            OAuth2AccessToken oAuth2AccessToken =
//                    defaultAuthorizationServerTokenServices.createAccessToken(oAuth2Authentication);
            log.info("获取token 成功：{}", token.getToken());

            response.setCharacterEncoding(CharsetUtil.UTF_8);
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            PrintWriter printWriter = response.getWriter();
            printWriter.append(objectMapper.writeValueAsString(token));
        } catch (IOException e) {
            throw new BadCredentialsException("Failed to decode basic authentication token");
        }
    }
}
